package com.binguo.thirdPay;

import com.binguo.common.util.JsonUtil;

import java.io.UnsupportedEncodingException;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


public class Sha1 {

    /**
     * 定义加密方式
     */
    private final static String KEY_SHA = "SHA";
    private final static String KEY_SHA1 = "SHA-1";
    /**
     * 全局数组
     */
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 构造函数
     */
    public Sha1() {

    }

    public static Map generateDataParam(String bizType,
                                        String eventId,
                                        String eventName,
                                        String distributorId,
                                        String distributorName
    ) throws Exception {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("bizType", bizType);
        map.put("distributorId", distributorId);
        map.put("distributorName", distributorName);
        map.put("eventId", eventId);
        map.put("eventName", eventName);
        return map;
    }

    public static String generateSign(String apiKey
            , String phone
            , String timeStamp
            , String productCode
            , String notifyUrl
            , String cstmOrderNo
            , String eventId
            , String account
            , Map<String, String> data
            , String securityKey
    ) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("apiKey", apiKey == null ? "" : apiKey);
        map.put("phone", phone == null ? "" : phone);
        map.put("timeStamp", timeStamp == null ? "" : timeStamp);
        map.put("productCode", productCode == null ? "" : productCode);
        map.put("notifyUrl", notifyUrl == null ? "" : notifyUrl);
        map.put("cstmOrderNo", cstmOrderNo == null ? "" : cstmOrderNo);


        String afterChange = null;
        try {

            if (data != null) {
                map.put("data", JsonUtil.toJson(data));
            }
            afterChange = SHA1(map, securityKey);
            System.out.println(afterChange);

            map.put("eventId", eventId == null ? "" : eventId);
            map.put("data", data);
            map.put("sign", afterChange);

            if (account != null) {
                map.put("account", account);
            }

            return JsonUtil.toJson(map);
        } catch (Exception e) {
        }

        return null;

    }


    /**
     * SHA 加密
     *
     * @param data 需要加密的字节数组
     * @return 加密之后的字节数组
     * @throws Exception
     */
    public static byte[] encryptSHA(byte[] data) throws Exception {
        // 创建具有指定算法名称的信息摘要
//	        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);  
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA1);
        // 使用指定的字节数组对摘要进行最后更新
        sha.update(data);
        // 完成摘要计算并返回
        return sha.digest();
    }

    /**
     * SHA 加密
     *
     * @param data 需要加密的字符串
     * @return 加密之后的字符串
     * @throws Exception
     */
    public static String encryptSHA(String data) throws Exception {
        // 验证传入的字符串

        // 创建具有指定算法名称的信息摘要
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
        // 使用指定的字节数组对摘要进行最后更新
        sha.update(data.getBytes());
        // 完成摘要计算
        byte[] bytes = sha.digest();
        // 将得到的字节数组变成字符串返回
        return byteArrayToHexString(bytes);
    }

    /**
     * 将一个字节转化成十六进制形式的字符串
     *
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteToHexString(byte b) {
        int ret = b;
        //System.out.println("ret = " + ret);
        if (ret < 0) {
            ret += 256;
        }
        int m = ret / 16;
        int n = ret % 16;
        return hexDigits[m] + hexDigits[n];
    }

    /**
     * 转换字节数组为十六进制字符串
     *
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(byteToHexString(bytes[i]));
        }
        return sb.toString();
    }


    /**
     * SHA1 安全加密算法
     *
     * @param maps        参数key-value map集合
     * @param securityKey
     * @return
     * @throws Exception
     */
    public static String SHA1(Map<String, Object> maps, String securityKey) throws Exception {
        //获取信息摘要 - 参数字典排序后字符串
        String decrypt = getOrderByLexicographic(maps);
        //拼接厂商秘钥
        StringBuffer sb = new StringBuffer(decrypt);
        sb.append(securityKey);

        //apiKeyNUFDJSOAcstmOrderNo201901101803002690data{"bizType":"","distributorId":"","distributorName":"","eventId":"","eventName":""}notifyUrlhttp://devwx.zj.chinaunicom.com/zjunicom-weixin/priviligeOrderController/acceptResultphone13282138659productCodeCMP305689154698608640timeStamp20190326140802
        //apiKeyNUFDJSOAcstmOrderNo201901101803002690data{"bizType":"","distributorId":"","distributorName":"","eventId":"","eventName":""}notifyUrlhttp://devwx.zj.chinaunicom.com/zjunicom-weixin/priviligeOrderController/acceptResultphone13282138659productCodeCMP305689154698608640timeStamp20190326140802cc1745453991ec29bfedd5f80a2d5bf0
        System.out.println(sb.toString());
        try {
            //指定sha1算法
            return encryptSHA(sb.toString());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new DigestException("签名错误！");
        }
    }

    /**
     * 获取参数的字典排序
     *
     * @param maps 参数key-value map集合
     * @return String 排序后的字符串
     */
    private static String getOrderByLexicographic(Map<String, Object> maps) {
        return splitParams(lexicographicOrder(getParamsName(maps)), maps);
    }

    /**
     * 获取参数名称 key
     *
     * @param maps 参数key-value map集合
     * @return
     */
    private static List<String> getParamsName(Map<String, Object> maps) {
        List<String> paramNames = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : maps.entrySet()) {
            paramNames.add(entry.getKey());
        }
        return paramNames;
    }

    /**
     * 参数名称按字典排序
     *
     * @param paramNames 参数名称List集合
     * @return 排序后的参数名称List集合
     */
    private static List<String> lexicographicOrder(List<String> paramNames) {
        Collections.sort(paramNames);
        return paramNames;
    }

    /**
     * 拼接排序好的参数名称和参数值
     *
     * @param paramNames 排序后的参数名称集合
     * @param maps       参数key-value map集合
     * @return String 拼接后的字符串
     */
    private static String splitParams(List<String> paramNames, Map<String, Object> maps) {
        StringBuilder paramStr = new StringBuilder();
        for (String paramName : paramNames) {
            paramStr.append(paramName);
            for (Map.Entry<String, Object> entry : maps.entrySet()) {
                if (paramName.equals(entry.getKey())) {
                    paramStr.append(String.valueOf(entry.getValue()));
                }
            }
        }
        return paramStr.toString();

    }


    /**
     * 利用java原生的类实现SHA256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256(String str) {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodestr;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }


}
